package com.atguigu.gulimall.cart.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.UserLoginRespVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 在执行目标方法之前，判断用户的登录状态，并封装给对应controller
 *
 * @author LaiSanShan
 * @date 2021-08-27
 */
public class CartInterceptor implements HandlerInterceptor {

    // 线程共享
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    // 业务执行之前，把用户信息存到threadLocal
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        UserInfoTo userInfoTo = new UserInfoTo();

        // 获取session中用户信息
        HttpSession session = request.getSession();
        UserLoginRespVo userLoginRespVo = (UserLoginRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (userLoginRespVo != null) {
            // 已登录
            userInfoTo.setUserId(userLoginRespVo.getId());
        }

        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                // 获取user-key这个cookie的值
                if (CartConstant.TEMP_USER_COOKIE_NAME.equalsIgnoreCase(cookieName)) {
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                }
            }
        }

        // 如果没有临时用户
        if (StringUtils.isBlank(userInfoTo.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }

        threadLocal.set(userInfoTo);
        return true;
    }

    // 业务执行之后，把user-key存到cookie中
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        UserInfoTo userInfoTo = threadLocal.get();
        // 没有user-key这个cookie
        if (!userInfoTo.getTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEM_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
